// src/pages/CompanyList/index.tsx
import {
  addCompany,
  deleteCompany,
  editCompany,
  getCompanyList,
} from '@/services/company';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import {
  Button,
  Form,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Tag,
  message,
} from 'antd';
import React, { useRef, useState } from 'react';
import { handleProTableRequest, callApi } from '@/utils/request';
import AuthorizedButton from '@/components/AuthorizedButton';
import { CompanyItem, CompanyQueryParams } from '@/types/company';

const CompanyList: React.FC = () => {
  const actionRef = useRef<any>(null);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [currentCompany, setCurrentCompany] = useState<CompanyItem | undefined>(
      undefined,
  );

  const handleAdd = () => {
    setIsEditing(false);
    setCurrentCompany(undefined);
    form.resetFields(); // 清空表单
    setModalVisible(true);
  };

  const handleEdit = (record: CompanyItem) => {
    setIsEditing(true);
    setCurrentCompany(record);
    form.setFieldsValue(record); // 设置表单初始值
    setModalVisible(true);
  };

  const handleDelete = async (record: CompanyItem) => {
    const result = await callApi(
        () => deleteCompany({ id: record.id }),
        { successMsg: '删除成功', errorMsg: '删除失败' }
    );

    if (result) {
      if (actionRef.current) {
        await actionRef.current.reload();
      }
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      let result;

      if (isEditing && currentCompany) {
        result = await callApi(
            () => editCompany({ ...values, id: currentCompany.id }),
            { successMsg: '编辑成功', errorMsg: '编辑失败' }
        );
      } else {
        result = await callApi(
            () => addCompany(values),
            { successMsg: '新增成功', errorMsg: '新增失败' }
        );
      }

      if (result) {
        setModalVisible(false);
        if (actionRef.current) {
          await actionRef.current.reload();
        }
      }
    } catch (error: any) {
      console.error('提交失败:', error);
      message.error(error?.message || '提交失败，请检查表单');
    }
  };

  const handleModalCancel = () => {
    setModalVisible(false);
    form.resetFields(); // 关闭弹窗时也清空表单
  };

  // 列定义
  const columns: ProColumns<CompanyItem>[] = [
    {
      title: '公司ID',
      dataIndex: 'id',
      search: false, // 不在查询表单中显示
      width: 80,
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      width: 150,
      formItemProps: {
        // 查询表单项配置
      },
    },
    {
      title: '公司编码',
      dataIndex: 'orgCode',
      search: false, // 不在查询表单中显示
      width: 100,
    },
    {
      title: '公司地址',
      dataIndex: 'address',
      search: false, // 不在查询表单中显示
      ellipsis: true, // 超出省略
      width: 150,
    },
    {
      title: '公司状态',
      dataIndex: 'status_dictText', // 显示字典文本
      valueType: 'select',
      valueEnum: {
        '1': { text: '启用', status: 'Success' },
        '0': { text: '禁用', status: 'Default' },
      },
      search: false, // 不在查询表单中显示
      render: (_, record) => (
          <Tag color={record.status === 1 ? 'success' : 'default'}>
            {record.status_dictText}
          </Tag>
      ),
      width: 100,
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactName',
      search: false, // 不在查询表单中显示
      width: 120,
    },
    {
      title: '联系人电话',
      dataIndex: 'contactPhone',
      search: false, // 不在查询表单中显示
      width: 120,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
          <Space size={10}>
            <AuthorizedButton
                type="link"
                size="small"
                icon={<EditOutlined />}
                onClick={() => handleEdit(record)}
                code="company_list_edit_btn" // 替换为实际权限码
            >
              编辑
            </AuthorizedButton>
            <Popconfirm
                title="确定删除此公司吗？"
                onConfirm={() => handleDelete(record)}
                okText="确定"
                cancelText="取消"
            >
              <AuthorizedButton
                  type="link"
                  size="small"
                  icon={<DeleteOutlined />}
                  danger
                  code="company_list_delete_btn" // 替换为实际权限码
              >
                删除
              </AuthorizedButton>
            </Popconfirm>
          </Space>
      ),
    },
  ];

  return (
      <PageContainer>
        <ProTable<CompanyItem, CompanyQueryParams>
            headerTitle="公司管理"
            actionRef={actionRef}
            rowKey="id"
            search={{
              labelWidth: 'auto',
            }}
            toolBarRender={() => [
              <AuthorizedButton
                  key="add"
                  type="primary"
                  onClick={handleAdd}
                  code="company_list_add_btn" // 替换为实际权限码
              >
                <PlusOutlined />
                新增
              </AuthorizedButton>,
            ]}
            request={async (params) => {
              const queryParams: CompanyQueryParams = {
                companyName: params.companyName,
                pageSize: params.pageSize,
                pageNum: params.current,
              };

              return handleProTableRequest<CompanyItem>(
                  () => getCompanyList(queryParams),
                  { errorMsg: '获取公司列表失败' }
              );
            }}
            columns={columns}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSizeOptions: ['10', '20', '30', '50'],
            }}
        />

        {/* 公司信息编辑/新增弹窗 */}
        <Modal
            title={isEditing ? '编辑公司' : '新增公司'}
            open={modalVisible}
            onOk={handleModalOk}
            onCancel={handleModalCancel}
            destroyOnClose // 关闭时销毁子元素，防止表单状态残留
            width={600}
        >
          <Form
              form={form}
              layout="vertical"
              preserve={false} // 配合 destroyOnClose 确保表单状态完全重置
          >
            <Form.Item
                name="companyName"
                label="公司名称"
                rules={[{ required: true, message: '请输入公司名称!' }]}
            >
              <Input placeholder="请输入公司名称" />
            </Form.Item>
            <Form.Item
                name="orgCode"
                label="公司编码"
                rules={[
                  { required: true, message: '请输入公司编码!' },
                  {
                    pattern: /^[A-Z0-9_]+$/,
                    message: '公司编码只能包含大写字母、数字和下划线',
                  },
                ]}
            >
              <Input placeholder="请输入公司编码" />
            </Form.Item>
            <Form.Item
                name="address"
                label="公司地址"
                rules={[{ required: true, message: '请输入公司地址!' }]}
            >
              <Input.TextArea placeholder="请输入公司地址" rows={2} />
            </Form.Item>
            <Form.Item
                name="status"
                label="公司状态"
                rules={[{ required: true, message: '请选择公司状态!' }]}
            >
              <Select placeholder="请选择状态">
                <Select.Option value={1}>启用</Select.Option>
                <Select.Option value={0}>禁用</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
                name="contactName"
                label="联系人姓名"
                rules={[{ required: true, message: '请输入联系人姓名!' }]}
            >
              <Input placeholder="请输入联系人姓名" />
            </Form.Item>
            <Form.Item
                name="contactPhone"
                label="联系人电话"
                rules={[
                  { required: true, message: '请输入联系人电话!' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码!' },
                ]}
            >
              <Input placeholder="请输入联系人电话" />
            </Form.Item>
          </Form>
        </Modal>
      </PageContainer>
  );
};

export default CompanyList;